package com.wephone.Student.ui;

import java.io.File;
import java.io.FileNotFoundException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.util.Util;

public class ZhidaoAddAnswerActivity extends BaseActivity {
	private String askId;
	private EditText answerEdit;
	private CheckBox anonymousCheck;
	private File photoSavedFile = null;
	private String photoSavedName = null;
	private boolean hasPhotoUpload = false;
	private ImageView userPhoto;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoAddAnswerActivity.this,BaseResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					Toast.makeText(getApplicationContext(), "回答添加成功", Toast.LENGTH_LONG).show();
					setResult(11);
					finish();
				}
			}
		};
		return handler;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1){
			if(photoSavedFile!=null && photoSavedFile.exists()){
				hasPhotoUpload = true;
				Bitmap bitmap = Util.getBitmap(getApplicationContext(),photoSavedFile.getPath(),200);
       		 	userPhoto.setImageBitmap(bitmap);
       		 	Util.saveMyBitmap(bitmap,photoSavedName,getApplicationContext());
			}else if(data!=null){
				Bundle bundle = data.getExtras();
				if(bundle!=null){
					Bitmap tmpbitmap = (Bitmap)bundle.get("data");
					if(tmpbitmap!=null){
						hasPhotoUpload = true;
						userPhoto.setImageBitmap(tmpbitmap);
		       		 	Util.saveMyBitmap(tmpbitmap,photoSavedName,getApplicationContext());
					}
				}
			}
   	 	}else if(requestCode==2){
	   	 	if(data!=null){
	   		 	Uri selectedImage = data.getData();
		        String[] filePathColumn = {MediaStore.Images.Media.DATA};
		        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
		        cursor.moveToFirst();
		        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		        String picturePath = cursor.getString(columnIndex);
		        cursor.close();
		        if(!TextUtils.isEmpty(picturePath)){
		        	 File userLogoFile = new File(picturePath);  
		        	 if(userLogoFile.exists()){
		        		 hasPhotoUpload = true;
		        		 Bitmap bitmap = Util.getBitmap(getApplicationContext(),picturePath,200);
		        		 userPhoto.setImageBitmap(bitmap);
		        		 Util.saveMyBitmap(bitmap,photoSavedName,getApplicationContext());
		        	 }
		         }
	   	 	}
   	 	}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhidao_add_answer);
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			askId = bundle.getString("askId");
			
			init();
		}
	}
	
	private void init(){
		answerEdit = (EditText)findViewById(R.id.add_zhidao_edit);
		anonymousCheck = (CheckBox)findViewById(R.id.add_comment_anonymous_check);
		userPhoto = (ImageView)findViewById(R.id.add_pic_pre_image);
		
		anonymousCheck.setChecked(ShareReferenceUtil.getIsNiming(getApplicationContext()));
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		findViewById(R.id.btn_top_right).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(answerEdit.getText().toString().trim().replace("\n", "").length()>0){
					RequestParams params = new RequestParams();
					params.put("id", askId);
					params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
					params.put("content", answerEdit.getText().toString());
					params.put("anonymous", anonymousCheck.isChecked()?"1":"0");
					if(hasPhotoUpload && photoSavedFile!=null && photoSavedFile.exists()){
						try {
							params.put("askimg1", photoSavedFile);
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
					}
					HttpClient.getInstance().post(Constants.API_ADD_ZHIDAO_ASK_REPLY_URL, params, getHandler());
					
					Toast.makeText(getApplicationContext(), "发布中", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(getApplicationContext(), "回答内容必须填写", Toast.LENGTH_LONG).show();
				}
			}
		});
		findViewById(R.id.btn_add_pic).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(ZhidaoAddAnswerActivity.this).setTitle("选择头像")
				.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						if(arg1==0){
							File rootFile = new File(Constants.IMAGE_PHOTO_TMP_PATH);
							if(!rootFile.exists()){
								rootFile.mkdirs();
							}
							photoSavedName = "addQuesPic_"+System.currentTimeMillis()+".jpg";
							photoSavedFile = new File(Constants.IMAGE_PHOTO_TMP_PATH+photoSavedName);
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoSavedFile));
		                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		                    startActivityForResult(intent, 1);
						}else{
							photoSavedName = "addQuesPic_"+System.currentTimeMillis()+".jpg";
							photoSavedFile = new File(Constants.IMAGE_PHOTO_TMP_PATH+photoSavedName);
							Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							startActivityForResult(i, 2);
						}
					}})
				.setNegativeButton("取消", null).show();
			}
		});
	}

}
